package com.cinema.dao;

import com.cinema.entity.Movie;
import com.cinema.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 电影数据访问对象
 */
public class MovieDAO {

    /**
     * 获取所有正在上映的电影
     */
    public List<Movie> findNowShowing() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Movie> movies = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM movies WHERE status = 'NOW_SHOWING' ORDER BY release_date DESC";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                movies.add(mapResultSetToMovie(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return movies;
    }

    /**
     * 根据条件搜索电影
     */
    public List<Movie> searchMovies(String title, String genre, String city,
                                  String startDate, String endDate,
                                  Double minPrice, Double maxPrice) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Movie> movies = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            StringBuilder sql = new StringBuilder();
            sql.append("SELECT DISTINCT m.* FROM movies m ");
            sql.append("LEFT JOIN showtimes s ON m.id = s.movie_id ");
            sql.append("LEFT JOIN cinemas c ON s.cinema_id = c.id ");
            sql.append("WHERE m.status = 'NOW_SHOWING' ");

            List<Object> params = new ArrayList<>();

            if (title != null && !title.trim().isEmpty()) {
                sql.append("AND m.title LIKE ? ");
                params.add("%" + title.trim() + "%");
            }

            if (genre != null && !genre.trim().isEmpty()) {
                sql.append("AND m.genre LIKE ? ");
                params.add("%" + genre.trim() + "%");
            }

            if (city != null && !city.trim().isEmpty()) {
                sql.append("AND c.city LIKE ? ");
                params.add("%" + city.trim() + "%");
            }

            if (startDate != null && !startDate.trim().isEmpty()) {
                sql.append("AND s.show_date >= ? ");
                params.add(startDate);
            }

            if (endDate != null && !endDate.trim().isEmpty()) {
                sql.append("AND s.show_date <= ? ");
                params.add(endDate);
            }

            if (minPrice != null) {
                sql.append("AND s.price >= ? ");
                params.add(minPrice);
            }

            if (maxPrice != null) {
                sql.append("AND s.price <= ? ");
                params.add(maxPrice);
            }

            sql.append("ORDER BY m.release_date DESC");

            pstmt = conn.prepareStatement(sql.toString());
            for (int i = 0; i < params.size(); i++) {
                pstmt.setObject(i + 1, params.get(i));
            }

            rs = pstmt.executeQuery();

            while (rs.next()) {
                movies.add(mapResultSetToMovie(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return movies;
    }

    /**
     * 根据ID获取电影详情
     */
    public Movie findById(Integer id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Movie movie = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM movies WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                movie = mapResultSetToMovie(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return movie;
    }

    /**
     * 添加电影
     */
    public boolean addMovie(Movie movie) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean success = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO movies (title, english_title, director, actors, genre, " +
                        "duration, rating, release_date, poster_url, trailer_url, synopsis, " +
                        "language, country, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, movie.getTitle());
            pstmt.setString(2, movie.getEnglishTitle());
            pstmt.setString(3, movie.getDirector());
            pstmt.setString(4, movie.getActors());
            pstmt.setString(5, movie.getGenre());
            pstmt.setInt(6, movie.getDuration());
            pstmt.setString(7, movie.getRating());
            pstmt.setDate(8, movie.getReleaseDate() != null ? new java.sql.Date(movie.getReleaseDate().getTime()) : null);
            pstmt.setString(9, movie.getPosterUrl());
            pstmt.setString(10, movie.getTrailerUrl());
            pstmt.setString(11, movie.getSynopsis());
            pstmt.setString(12, movie.getLanguage());
            pstmt.setString(13, movie.getCountry());
            pstmt.setString(14, movie.getStatus());

            int rows = pstmt.executeUpdate();
            success = rows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt);
        }

        return success;
    }

    /**
     * 更新电影信息
     */
    public boolean updateMovie(Movie movie) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean success = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE movies SET title = ?, english_title = ?, director = ?, actors = ?, " +
                        "genre = ?, duration = ?, rating = ?, release_date = ?, poster_url = ?, " +
                        "trailer_url = ?, synopsis = ?, language = ?, country = ?, status = ? " +
                        "WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, movie.getTitle());
            pstmt.setString(2, movie.getEnglishTitle());
            pstmt.setString(3, movie.getDirector());
            pstmt.setString(4, movie.getActors());
            pstmt.setString(5, movie.getGenre());
            pstmt.setInt(6, movie.getDuration());
            pstmt.setString(7, movie.getRating());
            pstmt.setDate(8, movie.getReleaseDate() != null ? new java.sql.Date(movie.getReleaseDate().getTime()) : null);
            pstmt.setString(9, movie.getPosterUrl());
            pstmt.setString(10, movie.getTrailerUrl());
            pstmt.setString(11, movie.getSynopsis());
            pstmt.setString(12, movie.getLanguage());
            pstmt.setString(13, movie.getCountry());
            pstmt.setString(14, movie.getStatus());
            pstmt.setInt(15, movie.getId());

            int rows = pstmt.executeUpdate();
            success = rows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt);
        }

        return success;
    }

    /**
     * 更新电影状态
     */
    public boolean updateMovieStatus(Integer movieId, String status) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean success = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE movies SET status = ? WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, status);
            pstmt.setInt(2, movieId);

            int rows = pstmt.executeUpdate();
            success = rows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt);
        }

        return success;
    }

    /**
     * 获取所有电影（管理员用）
     */
    public List<Movie> findAll() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Movie> movies = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM movies ORDER BY created_at DESC";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                movies.add(mapResultSetToMovie(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return movies;
    }

    /**
     * 将ResultSet映射为Movie对象
     */
    private Movie mapResultSetToMovie(ResultSet rs) throws SQLException {
        Movie movie = new Movie();
        movie.setId(rs.getInt("id"));
        movie.setTitle(rs.getString("title"));
        movie.setEnglishTitle(rs.getString("english_title"));
        movie.setDirector(rs.getString("director"));
        movie.setActors(rs.getString("actors"));
        movie.setGenre(rs.getString("genre"));
        movie.setDuration(rs.getInt("duration"));
        movie.setRating(rs.getString("rating"));
        movie.setReleaseDate(rs.getDate("release_date"));
        movie.setPosterUrl(rs.getString("poster_url"));
        movie.setTrailerUrl(rs.getString("trailer_url"));
        movie.setSynopsis(rs.getString("synopsis"));
        movie.setLanguage(rs.getString("language"));
        movie.setCountry(rs.getString("country"));
        movie.setStatus(rs.getString("status"));
        movie.setCreatedAt(rs.getTimestamp("created_at"));
        movie.setUpdatedAt(rs.getTimestamp("updated_at"));
        return movie;
    }
}
